package com.spring.demo.spring_boot.mapper;

import java.util.Date;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import com.spring.demo.spring_boot.base.mapper.BaseMapper;
import com.spring.demo.spring_boot.domain.TempUser;

/**
 * 
 * @author 王辉阳
 * @date 2017年8月1日 下午6:11:28
 * @description 用户映射器
 */
@Mapper
public interface UserMapper extends BaseMapper<TempUser> {
	// 查询后存入redis，建议以方法名
	@Cacheable(value = "findByName", keyGenerator = "keyGenerator")
	@Select("SELECT * FROM USER WHERE name = #{name}")
	List<TempUser> findByName(@Param("name") String username);

	/**
	 * 
	 * @author 王辉阳
	 * @date 2017年8月1日 下午6:18:41
	 * @description dynamic sql provider
	 */
	public class DynaSqlProvider {
		public String update(final TempUser user) {
			return new SQL() {
				{
					UPDATE("USER");
					if (user.getId() != null) {
						SET("id = #{id}");
					}
					if (user.getAge() != null) {
						SET("age = #{age}");
					}
					if (user.getName() != null) {
						SET("name = #{name}");
					}
					if (user.getCtime() != null) {
						SET("ctime = #{ctime}");
					} else {
						SET("ctime = " + new Date());
					}

					WHERE("id = #{id}");
				}
			}.toString();
		}
	}

	// 查询后存入redis，建议以方法名
	@Cacheable(value = "get", keyGenerator = "keyGenerator")
	@Select("SELECT * FROM USER WHERE id = #{id}")
	TempUser get(@Param("id") String id);

	@Select("SELECT * FROM USER  ")
	TempUser findAll();

	@Select("SELECT * FROM USER WHERE name like  #{name} ")
	List<TempUser> findUsers(String name);

	@UpdateProvider(type = DynaSqlProvider.class, method = "update")
	void update(TempUser user);

	@CacheEvict(value = "delete", keyGenerator = "keyGenerator")
	@Delete("delete from USER where id = #{id}")
	void delete(@Param("id") String id);

	@Insert("insert into houniao.user(id,name,age,ctime) values(#{id},#{name},#{age},#{ctime}) ")
	void save(TempUser user);

}